package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.annotation.Log;
import com.example.common.result.PageResult;
import com.example.common.result.Result;
import com.example.common.result.YiFeiException;
import com.example.entity.activiti.TaskInfo;
import com.example.entity.dto.CoptcDto;
import com.example.entity.dto.CoptdDto;
import com.example.entity.dto.FileUpload.FileListDto;
import com.example.entity.dto.GetCoptcListDto;
import com.example.entity.dto.SaleOrder.BatchUpdateCoptcDto;
import com.example.entity.dto.SaleOrder.BatchUpdateCoptcListDto;
import com.example.entity.dto.SaleOrder.DeleteCoptcDto;
import com.example.entity.dto.TCInfo;
import com.example.entity.dto.User.MyUser;
import com.example.entity.hz.HttpResult;
import com.example.entity.hz.MOCTA;
import com.example.entity.hz.ShenHe;
import com.example.entity.vo.Business.BatchUpdateCoptcListVo;
import com.example.entity.vo.Business.CoptcListVo;
import com.example.entity.vo.Business.CoptcPlus;
import com.example.entity.vo.CoptcGyVo;
import com.example.entity.vo.CoptcVo;
import com.example.entity.vo.CoptdFZzVo;
import com.example.entity.vo.CoptdVo;
import com.example.entity.yifei.*;
import com.example.entity.ymlConfig.YmlConfig;
import com.example.exception.BaseException;
import com.example.mapper.*;
import com.example.service.*;
import com.example.service.impl.ActFlowCommService;
import com.example.service.impl.FlowService;
import com.example.untils.HttpClientUtil;
import com.example.untils.SecurityUtils;
import com.example.untils.StringUtils;
import com.example.untils.TimeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LiangPandeng
 * @since 2024-02-28
 */
@RestController
@RequestMapping("/api/coptc")
@Api(tags = "客户订单相关接口")
@Slf4j
public class CoptcController {
    @Resource
    private CoptcMapper coptcMapper;


    @Resource
    private CopteService copteService;

    @Resource
    private CoptcService coptcService;

    @Autowired
    private CmsmqService cmsmqService;

    @Resource
    private CoptdService coptdService;

    @Resource
    private CopmaMapper copmaMapper;

    @Resource
    private CoptdMapper coptdMapper;

    @Resource
    private MoctaMapper moctaMapper;

    @Resource
    private CopthMapper copthMapper;

    @Resource
    private AdmmfMapper admmfMapper;

    @Resource
    private AttachMapper attachMapper;
    @Autowired
    private ActFlowCommService actFlowCommService;

    @Autowired
    private FileService fileService;

    @Resource
    private PurtbService purtbService;

    @Resource
    private CopmgMapper copmgMapper;

    @Resource
    private CopteMapper copteMapper;

    @Resource
    private CoptjService coptjService;

    @Resource
    private CoptdjhMapper coptdjhMapper;

    @Autowired
    private FlowService flowService;

    @Log("撤审客户订单")
    @ApiOperation("撤审客户订单")
    @PostMapping("/withdraw")
    public Result withdrawCoptc(@RequestParam(defaultValue = "") String TC001,
                             @RequestParam(defaultValue = "") String TC002) {
        if(StringUtils.isEmpty(TC001) || StringUtils.isEmpty(TC002)) {
            return Result.error("单别或单号为空");
        }
        Coptc coptc = coptcMapper.selectOne(new LambdaQueryWrapper<Coptc>().eq(Coptc::getTc001, TC001)
                .eq(Coptc::getTc002, TC002));
        if(coptc == null) {
            return Result.error("订单不存在");
        }
        ShenHe shenHe = new ShenHe();
        shenHe.setCom(YmlConfig.getYFCOMPANY());
        shenHe.setUser("DS");
        shenHe.setRq(TimeUtils.HZStdTime());
        shenHe.setType("UNDO");
        shenHe.setDb(coptc.getTc001());
        shenHe.setDh(coptc.getTc002());
        shenHe.setProgram("COPI06");

        HttpResult httpResult = HttpClientUtil.postHZ(shenHe);
        if(httpResult.getStatus().equals("成功")) {
            Coptc coptc1=new Coptc();
            coptc1.setTc048("0");
            coptcMapper.update(coptc1,new LambdaQueryWrapper<Coptc>().eq(Coptc::getTc001, TC001)
                    .eq(Coptc::getTc002, TC002));
            return Result.success("撤审成功");
        }
        return Result.success("撤审失败");
    }
    @Log("作废客户订单")
    @ApiOperation("作废客户订单")
    @PostMapping("/invalidate")
    public Result invalidate(@RequestParam(defaultValue = "") String TC001,
                                @RequestParam(defaultValue = "") String TC002) {
        if(StringUtils.isEmpty(TC001) || StringUtils.isEmpty(TC002)) {
            return Result.error("单别或单号为空");
        }
        Coptc coptc = coptcMapper.selectOne(new LambdaQueryWrapper<Coptc>().eq(Coptc::getTc001, TC001)
                .eq(Coptc::getTc002, TC002));
        if(coptc == null) {
            return Result.error("订单不存在");
        }
        if("Y".equals(coptc.getTc027())) {
            return Result.error("订单已审核,不能作废");
        }
//        ShenHe shenHe = new ShenHe();
//        shenHe.setCom("ZJHZ");
//        shenHe.setUser("DS");
//        shenHe.setRq(TimeUtils.HZStdTime());
//        shenHe.setType("UNDO");
//        shenHe.setDb(coptc.getTc001());
//        shenHe.setDh(coptc.getTc002());
//        shenHe.setProgram("COPI06");

//        HttpResult httpResult = HttpClientUtil.postHZ(shenHe);
//        if(httpResult.getStatus().equals("成功")) {
            Coptc coptc1=new Coptc();
//            coptc1.setTc048("0");
            coptc1.setTc027("V");
            coptcMapper.update(coptc1,new LambdaQueryWrapper<Coptc>().eq(Coptc::getTc001, TC001)
                    .eq(Coptc::getTc002, TC002));
            Coptd coptd=new Coptd();
            coptd.setTd021("V");
            coptdMapper.update(coptd,new LambdaQueryWrapper<Coptd>().eq(Coptd::getTd001,TC001).eq(Coptd::getTd002,TC002));
            return Result.success("作废成功");
//        }
//        return Result.success("作废失败");
    }

//    @Log("审核客户订单")
//    @ApiOperation("审核客户订单")
//    @PostMapping("/checkCoptc")
//    public Result checkCoptc(@RequestParam(defaultValue = "") String TC001,
//                             @RequestParam(defaultValue = "") String TC002) {
//        if(StringUtils.isEmpty(TC001) || StringUtils.isEmpty(TC002)) {
//            return Result.error("单别或单号为空");
//        }
//        Coptc coptc = coptcMapper.selectOne(new LambdaQueryWrapper<Coptc>().eq(Coptc::getTc001, TC001)
//                .eq(Coptc::getTc002, TC002));
//        if(coptc == null) {
//            return Result.error("订单不存在");
//        }
//        coptc.setTc027("Y");
//        coptcMapper.update(coptc, new LambdaQueryWrapper<Coptc>().eq(Coptc::getTc001, TC001).eq(Coptc::getTc002, TC002));
//        Coptd coptd = new Coptd();
//        coptd.setTd021("Y");
//        coptdMapper.update(coptd, new LambdaQueryWrapper<Coptd>().eq(Coptd::getTd001, TC001).eq(Coptd::getTd002, TC002));
//        return Result.success("审核成功");
//    }

    @Log("删除客户订单")
    @ApiOperation("删除客户订单")
    @PostMapping("/delete")
    public Result deleteCoptc(@RequestBody DeleteCoptcDto dto) {
        if(StringUtils.isEmpty(dto.getTc001()) || StringUtils.isEmpty(dto.getTc002())) {
            return Result.error("单别或单号为空");
        }
        Coptc coptc = coptcMapper.selectOne(new LambdaQueryWrapper<Coptc>().eq(Coptc::getTc001, dto.getTc001())
                .eq(Coptc::getTc002, dto.getTc002()));
        if(coptc == null) {
            return Result.error("订单不存在");
        }
        if("Y".equals(coptc.getTc027())) {
            return Result.error("单据已审核,不能删除");
        }else if("V".equals(coptc.getTc027())) {
            return Result.error("单据已作废,不能删除");
        }
        if("1".equals(coptc.getTc048())) {
            return Result.error("单据在审核中,不能删除");
        }else if("3".equals(coptc.getTc048())) {
            return Result.error("单据已审核,不能删除");
        }
        List<MOCTA> list = moctaMapper.selectList(new LambdaQueryWrapper<MOCTA>().
                eq(MOCTA::getTA026, dto.getTc001()).eq(MOCTA::getTA027, dto.getTc002()));
        if(list != null && list.size() > 0) {
            StringBuffer sb = new StringBuffer();
            for(MOCTA mocta : list) {
                sb.append(mocta.getTA001()).append("-").append(mocta.getTA002()).append(";");
            }
            return Result.error("已有下流单据, " + sb.toString());
        }
        List<Copth> copths = copthMapper.selectList(new LambdaQueryWrapper<Copth>().
                eq(Copth::getTH014, dto.getTc001()).eq(Copth::getTH015, dto.getTc002()));
        if(copths != null && copths.size() > 0) {
            StringBuffer sb = new StringBuffer();
            for(Copth copth : copths) {
                sb.append(copth.getTH001()).append("-").append(copth.getTH002())
                        .append("-").append(copth.getTH003()).append(";");
            }
            return Result.error("已有下流单据, " + sb.toString());
        }

        // 删除订单中的附件
        attachMapper.delete(new LambdaQueryWrapper<Attach>().eq(Attach::getCompanyid, YmlConfig.getYFCOMPANY())
                .eq(Attach::getParent, "COPI06").eq(Attach::getKeyvalues, dto.getTc001() + "||" + dto.getTc002()));

        coptdMapper.delete(new LambdaQueryWrapper<Coptd>().eq(Coptd::getTd001, dto.getTc001()).eq(Coptd::getTd002, dto.getTc002()));
        coptcMapper.delete(new LambdaQueryWrapper<Coptc>().eq(Coptc::getTc001, dto.getTc001()).eq(Coptc::getTc002, dto.getTc002()));

        coptdjhMapper.delete(new LambdaQueryWrapper<Coptdjh>().eq(Coptdjh::getTd001, dto.getTc001()).eq(Coptdjh::getTd002, dto.getTc002()));
        return Result.success("删除成功");
    }

//    @Log("修改客户订单")
//    @ApiOperation("修改客户订单")
//    @PostMapping("/modify")
//    public Result modifyCoptc(@RequestBody CoptcDto coptcDto) {
//        coptcDto.getCoptc().setREMARK(coptcDto.getCoptc().getTc015());
//        coptcDto.getCoptc().setTc015("");
//        coptcMapper.update(coptcDto.getCoptc(),
//                new LambdaQueryWrapper<Coptc>().eq(Coptc::getTc001, coptcDto.getCoptc().getTc001())
//                                                .eq(Coptc::getTc002, coptcDto.getCoptc().getTc002()));
//        coptdMapper.delete(new LambdaQueryWrapper<Coptd>().eq(Coptd::getTd001, coptcDto.getCoptc().getTc001())
//                .eq(Coptd::getTd002, coptcDto.getCoptc().getTc002()));
//
//
//        String creator = coptcDto.getCreator();
//        QueryWrapper<Admmf> admmfQueryWrapper = new QueryWrapper<>();
//        admmfQueryWrapper.eq("MF001",creator);
//        System.out.println(creator);
//        Admmf admmf = admmfMapper.selectOne(admmfQueryWrapper);
//        String usrGroup = admmf.getMf004();
//        for (Coptd coptd : coptcDto.getCoptdList()) {
//            coptd.setCompany(admmf.getCompany());
//            coptd.setCreator(creator);
//            coptd.setUsrGroup(usrGroup);
//            coptd.setCreateDate(TimeUtils.getNowTime());
//            coptd.setModifier("");
//            coptd.setModiDate("");
//            coptd.setFlag(new Double(1));
//            coptdMapper.insert(coptd);
//        }
//        return Result.success("修改成功");
//    }

    @Log("新增客户订单")
    @ApiOperation("新增客户订单")
    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody CoptcDto coptcDto) throws ExecutionException, InterruptedException {
        CompletableFuture<Result> futureResult = coptcService.add(coptcDto);
        // 等待异步任务完成并获取结果
        Result result = futureResult.get(); // 这里会阻塞直到异步任务完成
        // 返回结果给前端
        return result;
    }

    @Log("上报销售订单")
    @ApiOperation("上报销售订单")
    @PostMapping("/report")
    @Transactional
    public Result report(@RequestParam String TC001, @RequestParam String TC002, @RequestParam String leader, @RequestParam String departmentId) {
        if (StringUtils.isEmpty(TC001) || StringUtils.isEmpty(TC002)) {
            return Result.error("单别或单号为空");
        }
        MyUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser==null){
            return Result.error("用户名为空,请重新登录!");
        }
        String userName = loginUser.getUsername();
        if (StringUtils.isEmpty(userName)){
            return Result.error("用户名为空,请重新登录!");
        }
        String formkey = "coptc";
        String beanName = formkey + "ServiceImpl";
        //关联业务 bussinessKey
        String bussinessKey = formkey + ":" + TC001 + ":" + TC002;
        String id = TC001 +":"+ TC002;
        if (departmentId != null && departmentId.equals("90808")) {
            formkey = "coptc2";
        }
        Boolean b=actFlowCommService.isOnly(bussinessKey,formkey);
        Boolean b2 = coptcService.tc30Is0(TC001,TC002);
        ProcessInstance processInstance;
        if (b && b2) {
            processInstance= actFlowCommService.startProcess(formkey, beanName, bussinessKey, id, userName, leader);
        }
        else {
            return Result.error("有相同单据正在审核或该单据已审核完成！");
        }
        //获取流程实例id
        String processInstanceId = processInstance.getId();
        List<Task> taskList = actFlowCommService.myTaskList(userName);
        if (!CollectionUtils.isEmpty(taskList)) {
            for (Task task : taskList) {
                if (task.getAssignee().equals(userName) &&
                        task.getProcessInstanceId().equals(processInstanceId)) {
                    log.info("TaskprocessInstanceId is {}", task.getProcessInstanceId());
                    log.info("taskid is {}",task.getId());
                    actFlowCommService.completeProcess("同意", userName, task.getId(),"");
                }
            }
        }else {
            return Result.error("空任务！");
        }
        return Result.success("上报销售订单成功");

    }
    @Log("批量上报销售订单")
    @ApiOperation("批量上报销售单")
    @PostMapping("/reportlist")
    @Transactional
    public Result reportlist(
            @RequestBody List<TCInfo> tcInfoList
    ) {

        MyUser loginUser = SecurityUtils.getLoginUser();
        String userName = loginUser.getUsername();
        if (tcInfoList.isEmpty()) {
            return Result.error("单别或单号列表为空");
        }
        if (StringUtils.isEmpty(userName)){
            throw new BaseException("用户名为空");
        }
        String formkey = "coptc";
        String beanName = formkey + "ServiceImpl";
        tcInfoList.forEach(tcInfo -> {
            if (StringUtils.isEmpty(tcInfo.getTC001()) || StringUtils.isEmpty(tcInfo.getTC002())) {
                throw new BaseException("单别或单号为空");
            }
            String bussinessKey = formkey + ":" + tcInfo.getTC001() + ":" + tcInfo.getTC002();
            String id = tcInfo.getTC001() +":"+ tcInfo.getTC002();
            Boolean b=actFlowCommService.isOnly(bussinessKey,formkey);
            Boolean b2=coptcService.tc30Is0(tcInfo.getTC001(),tcInfo.getTC002());
            String leader = tcInfo.getLeader();
            ProcessInstance processInstance;
            if (b&&b2){
                processInstance= actFlowCommService.startProcess(formkey, beanName, bussinessKey, id, userName, leader);
            }
            else {
                throw new BaseException("批量单据中有单据正在审核或已审核！");
            }
            //获取流程实例id
            String processInstanceId = processInstance.getId();
            List<Task> taskList = actFlowCommService.myTaskList(userName);
            if (!CollectionUtils.isEmpty(taskList)) {
                for (Task task : taskList) {
                    if (task.getAssignee().equals(userName) &&
                            task.getProcessInstanceId().equals(processInstanceId)) {
                        log.info("ProcessInstanceId is {}", task.getProcessInstanceId());
                        log.info("taskid is {}",task.getId());
                        actFlowCommService.completeProcess("同意", userName, task.getId(),"");
                    }
                }
            }
            else {
                throw new BaseException("空任务！");
            }
        });
        return Result.success("批量上报销售订单成功!!!");
    }
    @ApiOperation("根据单别获取单号")
    @GetMapping("/selectTc002")
    public Result<String> selectTC002(String tc001) {
        String id = cmsmqService.getIdByType(tc001, "coptc");
        return Result.success(id);
    }

    @ApiOperation("订单单头信息列表")
    @PostMapping("/selectCoptcList")
    public Result<PageResult<CoptcListVo>> getCoptcList(@RequestParam(defaultValue = "1") Integer current,
                                                        @RequestParam(defaultValue = "10") Integer size,
                                                        @RequestBody GetCoptcListDto getCoptcListDto){
        //List<Coptc> coptcs = coptcMapper.selectList(null);
        PageResult<CoptcListVo> pageResult =  coptcService.selectPage(current, size, getCoptcListDto);
        return Result.success(pageResult);
    }

    @ApiOperation("根据单头查询单身详情")
    @GetMapping("/selectCoptd")
    public Result<CoptcVo> selectCoptd(String db, String dh) {
        QueryWrapper<Coptc> coptcQueryWrapper = new QueryWrapper<>();
        coptcQueryWrapper.eq("TC001",db)
                .eq("TC002",dh);

        CoptcPlus coptcPlus = coptcMapper.getCoptcPlus(db, dh);
        if (coptcPlus.getREMARK()!=null){
            coptcPlus.setTc015(coptcPlus.getREMARK());
        }
        coptcPlus.setVersion(String.format("%04d", copteMapper.getCopteVersion(db, dh)));
        Copte copte = copteMapper.selectOne(new LambdaQueryWrapper<Copte>().eq(Copte::getTE001, db).eq(Copte::getTE002, dh).eq(Copte::getTE029, "Y").orderByDesc(Copte::getCreateDate));
        if(copte != null) coptcPlus.setChangeReason(copte.getTE006());

        List<Attach> fileList = fileService.fileList(new FileListDto(db, dh, "COPI06", YmlConfig.getYFCOMPANY()));
        List<String> urls = new ArrayList<>();
        for(int i = 0; i < fileList.size(); i++) {
            String docId = fileList.get(i).getDocid();
            String fileName = fileList.get(i).getFilename();
            String url = "/files/" + docId.substring(3, 6) + "000" +
            "/" + docId + "/" + fileName;
            urls.add(url);
        }

//        Coptc coptc = coptcMapper.selectOne(coptcQueryWrapper);
//        CoptcPlus coptcPlus = new CoptcPlus();
//        BeanUtils.copyPropertiesIgnoreCase(coptc, coptcPlus);


        /*QueryWrapper<Copma> copmaQueryWrapper = new QueryWrapper<>();
        copmaQueryWrapper.eq("MA001",coptc.getTc004());
        Copma copma = copmaMapper.selectOne(copmaQueryWrapper);
        coptc.setUdf08(copma.getMa002());*/


        List<Coptd> coptdPlusList = coptdMapper.getCoptdPlusList(db, dh);
//        QueryWrapper<Coptd> coptdQueryWrapper = new QueryWrapper<>();
//        coptdQueryWrapper.eq("TD001",db).eq("TD002",dh);
//        List<Coptd> coptds = coptdMapper.selectList(coptdQueryWrapper);
//        List<CoptdPlus> coptdPlusList = new ArrayList<>();
//        for(Coptd coptd : coptds) {
//            CoptdPlus coptdPlus = new CoptdPlus();
//            BeanUtils.copyPropertiesIgnoreCase(coptd, coptdPlus);
//            coptdPlusList.add(coptdPlus);
//        }

        CoptcVo coptcVo =new CoptcVo();
        coptcVo.setCoptc(coptcPlus);

        if(!coptdPlusList.isEmpty()){
            coptdPlusList.stream().forEach(arr -> {
                arr.setTd012(arr.getUdf51());
                if (arr.getMg005()==null||arr.getMg005().equals("")){
                    List<Copmg> copmgs = copmgMapper.selectList(new LambdaQueryWrapper<Copmg>()
                            .eq(Copmg::getMg001, coptcPlus.getTc004()).eq(Copmg::getMg003, arr.getTd014()).eq(Copmg::getMg002,arr.getTd004()));
                    if (!copmgs.isEmpty()){
                        arr.setMg005(copmgs.get(0).getMg005());
                        arr.setMg006(copmgs.get(0).getMg006());
                    }
                }
                Double td010Double = this.coptdMapper.getTd010Double(coptcPlus.getTc004(), arr.getTd004());
                if (td010Double!=null){
                    arr.setNuclearPriceLs(td010Double);
                    if (arr.getTd011()>td010Double){
                        arr.setHistoricalunitprice(2);
                    }else if (arr.getTd011().equals(td010Double)){
                        arr.setHistoricalunitprice(1);
                    }else {
                        arr.setHistoricalunitprice(0);
                    }
                }
            });
        }

        coptcVo.setCoptdList(coptdPlusList);
        coptcVo.setUrls(urls);
        return Result.success(coptcVo);
    }

    @ApiOperation("根据单头查询单身详情 列表")
    @PostMapping("/selectCoptdList")
    public Result<List<CoptcVo>> selectCoptdList(@RequestBody List<String> list) {

        List<CoptcVo> res = new ArrayList<>();
        for(String s : list) {
            String[] strings = s.split("-");
            String TC001 = "";   String TC002 = "";
            if(strings.length == 2) {
                TC001 = strings[0];
                TC002 = strings[1];
            } else if (strings.length == 3) {
                TC001 = strings[0];
                TC002 = strings[1] + "-" + strings[2];
            }
            QueryWrapper<Coptc> coptcQueryWrapper = new QueryWrapper<>();
            coptcQueryWrapper.eq("TC001", TC001)
                    .eq("TC002", TC002);

            CoptcPlus coptcPlus = coptcMapper.getCoptcPlus(TC001, TC002);
            if (coptcPlus.getREMARK()!=null){
                coptcPlus.setTc015(coptcPlus.getREMARK());
            }
            List<Attach> fileList = fileService.fileList(new FileListDto(TC001, TC002, "COPI06", YmlConfig.getYFCOMPANY()));
            List<String> urls = new ArrayList<>();
            for(int i = 0; i < fileList.size(); i++) {
                String docId = fileList.get(i).getDocid();
                String fileName = fileList.get(i).getFilename();
                String url = "/files/" + docId.substring(3, 6) + "000" +
                        "/" + docId + "/" + fileName;
                urls.add(url);
            }

            List<Coptd> coptdPlusList = coptdMapper.getCoptdPlusList(TC001, TC002);
            CoptcVo coptcVo =new CoptcVo();
            coptcVo.setCoptc(coptcPlus);

            if(!coptdPlusList.isEmpty()){
                coptdPlusList.stream().forEach(arr -> {
                    arr.setTd012(arr.getUdf51());
                    if (arr.getMg005()==null||arr.getMg005().equals("")){
                        List<Copmg> copmgs = copmgMapper.selectList(new LambdaQueryWrapper<Copmg>()
                                .eq(Copmg::getMg001, coptcPlus.getTc004()).eq(Copmg::getMg003, arr.getTd014()).eq(Copmg::getMg002,arr.getTd004()));
                        if (!copmgs.isEmpty()){
                            arr.setMg005(copmgs.get(0).getMg005());
                            arr.setMg006(copmgs.get(0).getMg006());
                        }
                    }
                    Double td010Double = this.coptdMapper.getTd010Double(coptcPlus.getTc004(), arr.getTd004());
                    if(td010Double!=null){
                        if (arr.getTd011()>td010Double){
                            arr.setHistoricalunitprice(2);
                        }else if (arr.getTd011().equals(td010Double)){
                            arr.setHistoricalunitprice(1);
                        }else {
                            arr.setHistoricalunitprice(0);
                        }
                    }
                });
            }

            coptcVo.setCoptdList(coptdPlusList);
            coptcVo.setUrls(urls);
            res.add(coptcVo);
        }
        return Result.success(res);
    }

    @ApiOperation("查询生管确认日单身详情列表")
    @PostMapping("/selectCoptcVoList")
    public Result<List<CoptdVo>> selectCoptdListSg(@RequestBody CoptdVo coptdVo) {
        if(coptdVo!=null){
            if (!StringUtils.isEmpty(coptdVo.getOrderId())){
                coptdVo.setSize(coptdVo.getOrderId().length());
            }
        }
        List<CoptdVo> coptdList = this.coptdMapper.selectCoptdListSg(coptdVo);
        return Result.success(coptdList);
    }

    @ApiOperation("修改生管确认日单身")
    @PostMapping("/updateUdf03Integer")
    @Transactional
    public Result updateUdf03Integer(@RequestBody List<CoptdDto> coptdDots){
        try{
            MyUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser==null){
                return Result.error("请先登录!");
            }
            String userName = loginUser.getUsername();
            Integer i = this.coptdMapper.updateUdf03Integer(coptdDots);
            if (i>0){
                Set<String> stringSet = new HashSet<>();
                coptdDots.forEach(arr -> {
                   stringSet.add(arr.getLcid());
                });
               stringSet.forEach(arr -> {
                   this.flowService.completeTask("同意", userName, arr, "生管确认日修改成功进入二审");
               });
            }
            return Result.success();
        }catch (Exception e){
            throw new YiFeiException(500,"修改生管确认日单身发生异常:"+e.getMessage());
        }
    }

    @Log("修改客户订单")
    @ApiOperation("修改客户订单")
    @PostMapping("/updateCoptc")
    public Result updateCoptc(@RequestBody CoptcDto coptcDto) {
        // 将备注字段改为REMARK  设置原先的单头备注为空
        coptcDto.getCoptc().setREMARK(coptcDto.getCoptc().getTc015());
        coptcDto.getCoptc().setTc015("");
        return coptcService.updateCoptc(coptcDto);
    }

    @ApiOperation("批量修改客户订单 查询列表")
    @PostMapping("/batchUpdateCoptcList")
    public Result<List<BatchUpdateCoptcListVo>> batchUpdateCoptcList(@RequestBody BatchUpdateCoptcListDto dto) {
        return coptcService.batchUpdateCoptcList(dto);
    }

    @Log("批量修改客户订单 修改操作")
    @ApiOperation("批量修改客户订单 修改操作")
    @PostMapping("/batchUpdateCoptc")
    public Result batchUpdateCoptc(@RequestBody BatchUpdateCoptcDto dto) {
        return coptcService.batchUpdate(dto);
    }

//    @Resource
//    private UserLogMapper userLogMapper;
//
//    @Resource
//    private WorkshopMapper workshopMapper;

//    @DSTransactional
//    @ApiOperation("测试数据库")
//    @PostMapping("/testDBSwitch")
//    public Result test() {
//        userLogMapper.delete(new LambdaQueryWrapper<UserLog>()
//                .eq(UserLog::getId, "03ffdd27-793b-491d-8b93-dfac238d45e3"));
//        workshopMapper.deleteById(1);
////        List<UserLog> userLogs = userLogMapper.selectList(null);
////        List<Workshop> workshops = workshopMapper.selectList(null);
//        if(1 < 3) throw new CustomException("500", "111");
//        return Result.success( "");
//    }
    @PostMapping("/getCurStatus")
    @ApiOperation("获得当前单据的审核状态")
    public Result getStatus(@RequestParam String TC001,@RequestParam String TC002){
        String formKey="coptc";
        String businessKey=formKey+":"+TC001+":"+TC002;
        List<TaskInfo> curProcessState = actFlowCommService.getCurProcessState(businessKey, formKey);
        return Result.success(curProcessState);
    }

    @PostMapping("/coptcToCopteStatus/{TC001}/{TC002}")
    @ApiOperation("查看当前销售订单是否能添加新的变更单")
    public Result coptcToCopteStatus(@PathVariable String TC001,@PathVariable String TC002){
        Copte copte = copteService.getOne(new LambdaQueryWrapper<Copte>().eq(Copte::getTE001, TC001).eq(Copte::getTE002, TC002)
                .eq(Copte::getTE029, "N"));
        if(copte != null) {
            return Result.error("已存在未结束的变更单。");
        }
        Integer count = moctaMapper.selectCount(new LambdaQueryWrapper<MOCTA>().eq(MOCTA::getTA026, TC001).eq(MOCTA::getTA027, TC001));
        if(count > 0) {
            return Result.error("已存在工单。");
        }
        //TODO 中间表MOCLY上的

        count = purtbService.count(new LambdaQueryWrapper<Purtb>().eq(Purtb::getTb029, TC001).eq(Purtb::getTb030, TC002));
        if(count > 0) {
            return Result.error("已存在请购单。");
        }
        count = copthMapper.selectCount(new LambdaQueryWrapper<Copth>().eq(Copth::getTH014, TC001).eq(Copth::getTH015, TC002));
        if(count > 0) {
            return Result.error("已存在销货单。");
        }
        count = coptjService.count(new LambdaQueryWrapper<Coptj>().eq(Coptj::getTj018, TC001).eq(Coptj::getTj019, TC002));
        if(count > 0) {
            return Result.error("已存在销退单。");
        }
        return Result.success("可以添加变更单");
    }

    @GetMapping("/coptcGyVo")
    @ApiOperation("获取当前销售订单关联的所有信息")
    public Result<List<CoptcGyVo>> queryCoptcGyVo(@RequestParam String TC001,@RequestParam String TC002){
        return this.coptcService.queryCoptcGyVo(TC001, TC002);
    }

    @ApiOperation("销售订单查询风嘴组信息")
    @PostMapping("/queryCoptdFZz")
    public Result<Map<String,CoptdFZzVo>> queryCoptdFZz(@RequestBody CoptdFZzVo coptdFZzVo){
        return this.coptcService.queryCoptdFZz(coptdFZzVo);
    }

    @ApiOperation("批量修改订单计划交货日期")
    @PostMapping("/updateCopTdJhList")
    @Transactional
    public Result updateCopTdJhList(@RequestBody List<Coptdjh> copTdJhList){
        if (copTdJhList!=null){
           try{
               copTdJhList.forEach(arr -> {
                   Coptdjh coptdjh = this.coptdjhMapper.selectOne(new LambdaQueryWrapper<Coptdjh>().eq(Coptdjh::getTd001, arr.getTd001()).eq(Coptdjh::getTd002, arr.getTd002()).eq(Coptdjh::getTd003, arr.getTd003()));
                   if (coptdjh!=null){
                       this.coptdjhMapper.update(arr,new LambdaQueryWrapper<Coptdjh>().eq(Coptdjh::getTd001, arr.getTd001()).eq(Coptdjh::getTd002, arr.getTd002()).eq(Coptdjh::getTd003, arr.getTd003()));
                   }else {
                       this.coptdjhMapper.insert(arr);
                   }
               });
               return Result.success();
           }catch (Exception e){
               throw new YiFeiException(500, "修改订单计划交货日期发生异常"+e.getMessage());
           }
        }
        return Result.error("参数错误");
    }
}
